/**
 * 
 */
package br.com.ufrn.aipetro.ga.view.form;

import java.beans.PropertyChangeEvent;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import br.com.ufrn.aipetro.ga.controller.device.ProtocolController;
import br.com.ufrn.aipetro.ga.domain.entity.device.Protocol;
import br.com.ufrn.aipetro.ga.model.persist.hibernate.HibernateDaoFactory;
import br.com.ufrn.aipetro.ga.view.interfaces.View;

/**
 * @author Lucas
 * 
 */
public class FormProtocolFxmlController implements View<ProtocolController>,
		Initializable {

	private static final int INSERT_MODE = 0;
	private static final int UPDATE_MODE = 1;

	private int editMode;
	private ProtocolController controller;

	@FXML private TextField tfdProtocolName;

	public FormProtocolFxmlController() {
		this.editMode = INSERT_MODE;
		initView(new ProtocolController(new HibernateDaoFactory()));
	}

	@FXML
	public void cancelForm() {
		// TODO Fechar form
	}

	@FXML
	private void close() {
	}

	@Override
	public void initialize(URL arg0, ResourceBundle arg1) {
	}

	@Override
	public void initView(ProtocolController controller) {
		this.controller = controller;
		this.controller.registerView(this);
	}

	private void insertProtocol() {
		controller.changeName(tfdProtocolName.getText());
		controller.persistInsert();
		this.editMode = UPDATE_MODE;
	}
	
	private void loadControllerToForm() {
		tfdProtocolName.setText(controller.getModel().getName());
	}

	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if (evt.getPropertyName().equals(Protocol.NAME_PROPERTY))
			tfdProtocolName.setText((String) evt.getNewValue());
	}

	@FXML
	public void saveForm() {
		if (this.editMode == INSERT_MODE)
			insertProtocol();
		else
			updateProtocol();
	}

	private void updateProtocol() {
		controller.changeName(tfdProtocolName.getText());
		controller.persistUpdate();
	}

	@Override
	public void modelChange() {
		editMode = UPDATE_MODE;
		loadControllerToForm();
	}

}
